<template>
  <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" append-to-body title="文档列表" width="800px" :visible.sync="show" @closed="resetDialog(1)">
    <div class="wrapper">
      <el-button type="primary" size="small"
                 @click="Visible=true">添加文档
      </el-button>
      <!-- 表格数据 -->
      <el-table style="margin-top: 15px" :data="tableData" v-loading="listLoading" border>
        <el-table-column label="ID" prop="ID" width="50" align="center"/>
        <el-table-column label="标题" prop="Title" width="150" align="center"/>
        <el-table-column label="时间" prop="times" width="150" align="center"/>
        <el-table-column label="文档" align="center">
          <template v-slot="{ row }">
            <el-button v-if="row.URL" size="small" icon="el-icon-document" title="查看" @click="openVideo(row.URL)">
              查看文档
            </el-button>
            <span v-else>无文档</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template v-slot="{ row,$index }">
            <!--            <el-button type="text" title="查看" @click="handle(row, true)">查看</el-button>-->
            <el-button style="color:#f46162;" type="text" title="删除" @click="handleDelete(row,$index)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 查看 or 新增-->
      <el-dialog append-to-body v-loading="vUploadLoading" element-loading-text="文档上传中，请勿操作"
                 element-loading-spinner="el-icon-loading"
                 element-loading-background="rgba(0, 0, 0, 0.8)" :title="findData.ID ? '查看' : '新增'"
                 width="400px" :visible.sync="Visible" @closed="resetDialog(2)">
        <el-form size="small" class="formRow" label-position="top">
          <el-form-item label="标题" prop="Title">
            <el-input v-model="findData.Title"></el-input>
          </el-form-item>
          <el-form-item label="时间" prop="times">
            <el-input-number v-model="findData.times" controls-position="right" :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="文档上传（txt文件）">
            <div v-if="!findData.readonly">
              <el-upload
                  class="upload-demo"
                  action=""
                  :on-preview="onPreview"
                  :before-upload="beforeUpload"
                  accept=".txt"
                  :limit="1"
                  :http-request="onRequest"
                  :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </div>
            <el-button icon="el-icon-document" v-else @click="openVideo(findData.URL)">查看文档</el-button>
          </el-form-item>
        </el-form>

        <div slot="footer">
          <el-button v-if="!findData.readonly" type="primary" @click="onSubmit">提交</el-button>
        </div>
      </el-dialog>
      <!--  播放文档  -->
      <el-dialog append-to-body title="查看文档" width="800px" :visible.sync="textShow">
      <pre style="width: 100%;
    white-space: pre-wrap;">{{ textContent }}</pre>
      </el-dialog>
    </div>
  </el-dialog>

</template>

<script>
import {
  Add_document_information,
  Delete_document_information,
  Query_document_information,
  uploadUrl
} from "@/api"
import moment from "moment"
import axios from "axios";

export default {
  name: "document_list",
  props: {},
  data() {
    return {
      show: false,
      // 加载
      listLoading: false,
      // 详情弹窗
      Visible: false,
      // 搜索用户相关
      paramsState: {
        id: '',
        startpoint: 1,
        nums: 10,
        total: 0
      },
      // 用户列表相关
      tableData: [],
      // 详情加载中
      loading: false,
      textShow: false,
      textContent: "",
      // 操作的数据信息
      findData: {
        Title: "",
        times: "",
        URL: ""
      },
      fields: [
        {label: '标题', prop: 'Title', width: '', align: 'center'},
        {label: '时间', prop: 'times', width: '130', align: 'center'},
        {label: '链接', prop: 'URL', width: '', align: 'center'}
      ],
      vUploadLoading: false,
      fileList: [
        // {
        //   name: "测试.mp4",
        //   url: "http://"
        // }
      ]
    }
  },
  methods: {
    sendParentData() {
      this.$emit("change", this.tableData.map(item => item.ID).join(','))
    },
    open(ids) {
      console.log(ids)
      this.tableData = [];
      ids.forEach((id) => {
        Query_document_information({id}).then(result => {
          this.tableData.push(result[0]);
        })
      })

    },
    openVideo(url) {
      fetch(url)
          .then(response => {
            // 检查响应状态
            if (!response.ok) {
              throw new Error('文件请求失败');
            }
            // 返回响应的文本内容
            return response.text();
          })
          .then(fileContent => {
            // 在页面上显示文件内容
            this.textContent = fileContent;
            this.$nextTick(() => {
              this.textShow = true;
            })
          })
          .catch(error => {
            // 处理错误
            console.error('发生错误:', error);
          });


    },
    async uploadChunk(option, option2) {
      console.log(option, option2)
      const formData = new FormData();
      formData.append('total', option2.totalPages);
      formData.append('index', option2.index);
      formData.append('mainway', 'text');
      formData.append('filename', option2.filename);
      formData.append('data', option.chunk);

      // 使用Axios或其他HTTP库发送请求
      await axios.post(uploadUrl, formData, {
        headers: {'Content-Type': 'multipart/form-data'}
      })
          .then(response => {
            console.log(option2.index + '：分片上传成功:', response);
            if (option2.index == option2.totalPages) {
              console.log('分片上传结束:', response);
              // response.data.path
              this.fileList = [
                {
                  name: option2.filename,
                  url: response.data.path
                }
              ]
              this.vUploadLoading = false;
            }
          })
          .catch(error => {
            console.error('分片上传失败:', error);
          });
    },
    beforeUpload(file) {
      console.log(file)
      const isVideo = file.type.startsWith('text/plain');
      if (!isVideo) {
        this.$message.error('只能上传txt文件！');
      }
      return isVideo;
    },
    onRequest(a, b, c) {
      console.log(a.file);
      this.vUploadLoading = true;
      let _this = this;
      this.fileList = [];
      const file = a.file;
      const fileSize = file.size;
      const CHUNK_SIZE = 2 * 1024 * 1024; // 每个分片的大小
      let offset = 0;
      let totalPages = Math.ceil(fileSize / CHUNK_SIZE);
      let index = 1;
      let filename = Date.now() + '.txt';

      while (offset < fileSize) {
        const chunkSize = Math.min(CHUNK_SIZE, fileSize - offset);
        const chunk = file.slice(offset, offset + chunkSize);

        _this.uploadChunk({
          chunk, offset, fileSize
        }, {
          filename, totalPages, index
        });
        // _this.uploadChunk(totalPages, index, file,);
        index++;
        offset += chunkSize;
      }

    },
    onPreview(file) {
      if (file.url) {
        this.openVideo(file.url);
      }
    },
    change(file) {
      let _this = this
      console.log(file.raw)
      let reader = new FileReader()
      reader.onload = function (event) {
        let base64 = event.target.result
        _this.findData.headimg = base64
      }
      reader.readAsDataURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const types = ['image/jpeg', 'image/png']
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!types.includes(file.type)) {
        this.$message.error('上传头像图片只能是 JPG 和 PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    resetDialog(index) {
      this.findData = {};
      this.fileList = [];
      if (index === 1) {
        this.tableData = [];
      }
    },
    // 保存
    onSubmit() {
      let file = this.fileList;
      if (file.length <= 0) {
        this.$message.error("请上传文档")
        return
      }
      let params = {
        ...this.findData,
        URL: file[0].url,
        url: file[0].url,
        Url: file[0].url,
      }
      console.log(params, "提交参数")

      Add_document_information(params).then(result => {
        console.log(result.data[0].id, "文档上传")
        this.tableData.push({
          ...params,
          ID: result.data[0].id
        })
        this.sendParentData();
        // this.$message.success(result.msg)
        this.Visible = false
      })
    },
    // 显示详情
    handle(row, readonly = false) {
      let params = {
        ...row,
        readonly
      }
      // this.fileList = [
      //   {
      //     name: "文档信息",
      //     url: params.URL
      //   }
      // ]
      this.findData = params
      this.Visible = true
    },
    // 删除用户
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData.splice(index, 1);
        this.sendParentData()
        // Delete_document_information({id: row.ID}).then(() => {
        //   this.$message({
        //     type: 'success', message: '删除成功!'
        //   })
        //   this.tableData.splice(index, 1);
        // })
      }).catch(() => {

      })
    }
  }
}
</script>

<style lang="scss" scoped>

.wrapper {

  .label {
    font-size: 14px;
    color: #333;
    padding-bottom: 10px;
  }
}

::v-deep .el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

::v-deep .el-dialog__body {
  padding: 10px 20px;
}

.formRow {

  &.disabled {
    pointer-events: none;
  }


  .el-col {
    padding: 8px 0;

    .label {
      font-weight: 500;
      margin-right: 10px;
      color: #444;
    }

    .headimg_view {
      margin-left: 50%;
      transform: translateX(-50%);
      overflow: hidden;

      .avatar {
        width: 120px;
        height: 120px;
        font-size: 0;
      }

      ::v-deep .image-slot {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        background-color: #eee;

        .iocn {
          font-size: 20px;
        }

        span {
          font-size: 14px;
        }
      }
    }
  }

  .sourceList {
    .item {
      padding: 10px;
      background-color: #f8f8f8;
      border-bottom: 1px solid #ddd;

      &:last-child {
        border-bottom: 0;
      }

      .box {
        padding: 5px 0;
        display: flex;

        .label {
          color: #666;
          padding-right: 20px;
        }
      }
    }
  }
}

.dataList {
  margin-bottom: 20px;

  .desc {
    margin-top: 10px;
    color: #888;
  }

  .dataTitle {
    font-weight: 500;
    color: #333;
  }
}

//::v-deep .el-form-item__label {
//  width: 100%;
//}

.flex {
  display: flex;

  span {
    b {
      color: #f46162;
    }
  }

  &.between {
    justify-content: space-between;
  }
}

.videoView {
  width: 100%;
  height: 400px;
}
</style>
